package com.xy.job.admin.common

import kotlin.reflect.full.memberProperties

inline fun <reified T : Any> buildEntityFromMap(map: Map<String, Any?>): T {
    val clazz = T::class
    val noArgConstructor = clazz.constructors.find { it.parameters.isEmpty() }
        ?: throw RuntimeException("can not find noArgConstructor from ${clazz.qualifiedName}")
    val entity = noArgConstructor.call()
    val name2propertyMap = clazz.memberProperties.associateBy { it.name }
    map.forEach { (propertyName, value) ->
        val property = name2propertyMap[propertyName] ?: return@forEach
        when (property) {
            is kotlin.reflect.KMutableProperty<*> -> property.setter.call(entity, value)
            else -> throw RuntimeException("can not set property ${property.name} from ${clazz.qualifiedName}")
        }
    }
    return entity
}